package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.client.article.IArticleClient;
import com.heima.client.user.IApUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.BaiduScanService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.CommentPageDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticleConfig;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Lijx
 * @Date 2024-08-01 11:17
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private BaiduScanService baiduScanService;
    @Autowired
    private IApUserClient apUserClient;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 发布评论
     * @param articleId
     * @param content
     * @return
     */
    @Override
    public ResponseResult saveComment(Long articleId, String content) {
        //验证用户是否登录
        // 如果id无效，或者是0(游客)：流程结束
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        //查询文章配置信息，是否允许评论
        ResponseResult configInfo = articleClient.getArticleConfig(articleId);
        if (configInfo.getCode() != 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticleConfig articleConfig = JSON.parseObject(JSON.toJSONString(configInfo.getData()), ApArticleConfig.class);
        //如果不允许评论
        if (!articleConfig.getIsComment()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //查询登录用户信息
        ResponseResult userInfo = apUserClient.getUserInfo(userId);
        if (userInfo.getCode() != 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApUser user = JSON.parseObject(JSON.toJSONString(userInfo.getData()), ApUser.class);

        //评论内容不能超过140字
        if (content.length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //验证发布的评论是否合规
        boolean res = baiduScanService.scanText(content);
        if (!res) { //不合格
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApComment apComment = new ApComment();
        apComment.setContent(content);
        apComment.setAuthorId(userId);
        apComment.setAuthorName(user.getName());
        apComment.setCreatedTime(new Date());
        apComment.setEntryId(articleId);
        apComment.setType(0);
        apComment.setFlag(0);
        apComment.setLikes(0);
        apComment.setReply(0);
        mongoTemplate.save(apComment);

        //发送消息
        kafkaTemplate.send("article_comment",JSON.toJSONString(articleId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 展示文章评论列表
     * @param articleId
     * @param minDate
     * @return
     */
    @Override
    public ResponseResult getCommentList(Long articleId, Object minDate,Integer index) {
        Date date = null;

        //判断参数类型是哪种格式
        if (minDate instanceof Long) {
            Long time = (Long) minDate;
            //转换为data日期格式
            date = new Date(time);
        }else if (minDate instanceof Date) {
            date = (Date) minDate;
        }

        // 计算跳过的记录数
        int skip = (index - 1) * 10;

        //查询评论列表
        List<ApComment> commentList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(articleId)
                        .and("createdTime").lte(date))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .skip(skip).limit(10), ApComment.class);

        //判断当前文章是否有评论
        if (commentList != null && commentList.size() >0) {
            //查询当前登录用户，是否点赞评论
            Integer userId = ApThreadLocalUtil.get();
            if (userId != null && userId != 0 ) {
                List<ApCommentLike> likeList = mongoTemplate.find(Query.query(Criteria.where("authorId").is(userId)),
                        ApCommentLike.class);
                //通过stream流收集评论id
                if (likeList != null && likeList.size() >0) {
                    List<String> list = likeList.stream().map(ApCommentLike::getCommentId).collect(Collectors.toList());
                    //遍历集合
                    for (String commentId : list) {
                        for (ApComment apComment : commentList) {
                            if (apComment.getId().equals(commentId)) {
                                apComment.setOperation(0);
                            }
                        }
                    }
                }
            }
        }

        //将评论列表返回
        return ResponseResult.okResult(commentList);
    }

    /**
     * 文章评论点赞
     * @param commentId
     * @param operation
     * @return
     */
    @Override
    public ResponseResult commentlike(String commentId, Integer operation) {

        //验证用户是否登录
        // 如果id无效，或者是0(游客)：流程结束
        Integer userId = ApThreadLocalUtil.get();
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        //查询这条评论数据
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentId)),
                ApComment.class);
        if (apComment == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是点赞还是取消点赞
        if (operation == 0) { //0表示点赞
            Integer likes = apComment.getLikes();
            apComment.setLikes(likes+1);
            //重新更新保存评论信息
            mongoTemplate.save(apComment);

            //记录当前用户对于当前评论的数据
            ApCommentLike commentLike = new ApCommentLike();
            commentLike.setCommentId(commentId);
            commentLike.setAuthorId(userId);
            mongoTemplate.save(commentLike);
        }else { //取消点赞
            Integer likes = apComment.getLikes();
            apComment.setLikes(likes-1);
            //重新更新保存评论信息
            mongoTemplate.save(apComment);

            //删除当前用户对于当前评论的数据
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)
                    .and("authorId").is(userId)),
                    ApCommentLike.class);
        }

        return ResponseResult.okResult(apComment.getLikes());
    }

    @Override
    public ResponseResult pageComment(CommentPageDto pageDto) {
        return null;
    }
}
